<template>
    <div class="tcenter">
        <el-form :model="userData">
            <el-form-item label="邮箱">
                <el-input v-model="userData.email" />
            </el-form-item>
            <el-form-item label="密码">
                <el-input v-model="userData.password" type="password" />
            </el-form-item>
            <el-button type="warning" @click="login()">登录</el-button>
        </el-form>
    </div>
</template>
  
<script setup>
import api from '@/api/api';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

const store = new useStore();
const router = new useRouter();



const userData = ref({
    email: '',
    password: ''
})

const login = () => {
    if (userData.value.username == '' || userData.value.email == '' || userData.value.password == '') {
        ElMessage({
            message: '内容不能为空',
            type: 'error'
        })
    }
    else if (/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(userData.value.email) != true) {
        ElMessage({
            message: '无效的邮箱',
            type: 'error'
        })
    }
    else {
        api.userLogin(userData)
            .then(ret => {
                if (ret.flag) {
                    store.dispatch('LoginSuccess', ret.result)
                    ElMessage({
                        message: '登录成功',
                        type: 'success'
                    })
                    setTimeout(() => {
                        router.push({ name: 'index' });
                    }, 1500);
                }
                else {
                    ElMessage({
                        message: '登录失败，检查重试',
                        type: 'error'
                    })
                }
            })
    }
}



</script>

<style scoped>
.el-input {
    width: 250px;
}

.tcenter {
    width: 300px;
    margin: 0px auto;
}
</style>
  